package com.zjq.authoritysystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjq.authoritysystem.dto.RolePermissionDto;
import com.zjq.authoritysystem.entity.Role;
import com.zjq.authoritysystem.mapper.RoleMapper;
import com.zjq.authoritysystem.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjq.authoritysystem.vo.query.RoleQueryVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author BetOnMe
 * @since 2023-09-18
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public Page listByPage(RoleQueryVo roleQueryVo) {
        return page(new Page<>(roleQueryVo.getCurrent(), roleQueryVo.getSize()),
                new QueryWrapper<Role>()
                        .eq("is_delete", Role.IS_DELETE_NO)
                        .like(StringUtils.isNotBlank(roleQueryVo.getSearch()), "name", roleQueryVo.getSearch())
                        .orderByAsc("id"));
    }

    @Override
    public boolean delete(Integer id) {
        return this.update(new UpdateWrapper<Role>().set("is_delete", Role.IS_DELETE_YES).eq("id", id));
    }

    @Override
    public List<Role> getByCode(String code) {
        return this.list(new QueryWrapper<Role>().eq("code", code).eq("is_delete", Role.IS_DELETE_NO));
    }

    @Override
    public boolean saveRolePermissions(RolePermissionDto rolePermissionDto) {
        // 先删除角色原有的权限信息
        baseMapper.deleteRolePermissionByRoleId(rolePermissionDto.getRoleId());
        return baseMapper.saveRolePermission(rolePermissionDto.getRoleId(), rolePermissionDto.getPermissionIds()) > 0;
    }
}
